<template>
  <div class="user">
    <n-spin :show="loading">
      <template v-if="userInfo">
        <!-- {{ userInfo }} -->
        <n-card class="user-card">
          <div class="user-header">
            <div class="user-info-change">
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-button size="small" @click="showEditModal=true" circle>
                    <span class="iconfont">&#xe8b7;</span>
                  </n-button>
                </template>
                编辑个人资料
              </n-tooltip>
            </div>
            <div class="user-avatar">
              <n-image
                class="user_img"
                :src="store.state.baseURL + userInfo.userImg"
                :preview-disabled="true"
                object-fit="cover"
              />
              <n-button
                circle
                class="user-sex"
                :type="userInfo.sex == 'M' ? 'info' : 'error'"
              >
                <span class="iconfont">{{ userInfo.sex == "M" ? "男" : "女" }}</span>
              </n-button>
            </div>
            <div class="user-details">
              <div class="user-name">
                <h2>{{ userInfo.nickName || userInfo.username }}</h2>
              </div>
              <p class="user-id">ID: {{ userInfo.id }}</p>
              <div class="user-stats">
                <div class="stat-item" v-for="(stat, index) in userStats" :key="index">
                  <span class="number">{{ userInfo[stat.key] || 0 }}</span>
                  <span class="label">{{ stat.label }}</span>
                </div>
              </div>
            </div>
            <n-popconfirm
              positive-text="确定"
              negative-text="取消"
              @positive-click="handleLogout"
            >
              <template #trigger>
                <n-button class="logout-btn"> 退出登录 </n-button>
              </template>
              确定要退出登录吗？
            </n-popconfirm>
          </div>
          <n-tabs type="card">
            <n-tab-pane name="commentList" tab="我的评论">
              <div class="tab-content" v-if="commentList.length > 0">
                <userComment :data="commentList" />
              </div>
              <div class="tab-content" v-else>
                <n-empty description="暂无评分" />
              </div>
            </n-tab-pane>
            <n-tab-pane name="collectList" tab="我的收藏">
              <div class="tab-content" v-if="collectList.length > 0">
                <userCollect :data="collectList" />
              </div>
              <div class="tab-content" v-else>
                <n-empty description="暂无评分" />
              </div>
            </n-tab-pane>
          </n-tabs>
        </n-card>
      </template>
    </n-spin>

    <!-- 编辑资料对话框 -->
    <n-modal v-model:show="showEditModal" preset="dialog" title="编辑个人资料">
      <!-- {{ editForm }} -->
      <n-form ref="changeInfoFormRef" :model="editForm">
        <n-form-item label="昵称" path="nickName">
          <n-input v-model:value="editForm.nickName" placeholder="请输入新昵称" />
        </n-form-item>
        <n-form-item label="性别" path="sex">
          <n-radio-group v-model:value="editForm.sex">
            <n-radio value="M">男</n-radio>
            <n-radio value="F">女</n-radio>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="头像" path="userImg">
          <n-upload
            v-model:file-list="editForm.userImg"
            list-type="image-card"
            accept=".jpg,.jpeg,.png,.gif"
            :max="1"
            @change="handleUploadChange"
          >
            上传头像
          </n-upload>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showEditModal = false">取消</n-button>
          <n-button type="primary" @click="handleSaveInfo">更新</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import {
  useMessage,
  NSpin,
  NImage,
  NCard,
  NButton,
  NTabs,
  NTabPane,
  NEmpty,
  NTooltip,
  NModal,
  NForm,
  NFormItem,
  NInput,
  NRadioGroup,
  NRadio,
  NSpace,
  NPopconfirm,
  NUpload,
} from "naive-ui";
import userComment from "@/components/userComment.vue";
import userCollect from "@/components/userCollect.vue";
import { onMounted, computed, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { request } from "@/utils/request";
const store = useStore();
const message = useMessage();
const router = useRouter();
const loading = ref(true);
const userInfo = ref(null);
const showEditModal = ref(false);

const userStats = [
  { key: "average_score", label: "均分" },
  { key: "comment_count", label: "评论" },
  { key: "comment_likes", label: "获赞" },
  { key: "comment_dislikes", label: "被踩" },
  { key: "collect_count", label: "收藏" },
];
const changeInfoFormRef = ref(null);
const editForm = ref({
  nickName: "",
  sex: 0,
  userImg: [],
});

onMounted(async () => {
  if (store.state.loginInfo == null) {
    router.push("/login");
  } else {
    await getUserInfo()
  }
});
const getUserInfo = () => {
  request({
    url: "/login/",
    method: "post",
    data: store.state.loginInfo,
  }).then((res) => {
    if (res.code === 200) {
      userInfo.value = res.data;
      console.log("userInfo", userInfo.value);
      store.commit("setUserInfo", userInfo.value);
      loading.value = false;
      getComments();
      getCollect();
    } else {
      localStorage.clear();
      store.commit("setUserInfo", null);
      store.commit("setLoginInfo", null);
      message.error(res.message);
      router.push("/login");
    }
  });
};
const commentList = ref([]);
const getComments = () => {
  request({
    url: "/get_comment/?user_id=" + userInfo.value.id,
    method: "GET",
  }).then((res) => {
    if (res.code === 200) {
      commentList.value = res.data;
    }
  });
};
const collectList = ref([]);
const getCollect = () => {
  request({
    url: "/get_user_collect/?user_id=" + userInfo.value.id,
    method: "GET",
  }).then((res) => {
    if (res.code === 200) {
      console.log("collectList", res.data);
      collectList.value = res.data;
    }
  });
};


const handleSaveInfo = async () => {
  let IsNickName = editForm.value.nickName == userInfo.value.nickName;
  let IsSex = editForm.value.sex == userInfo.value.sex;
  let IsUserImg = editForm.value.userImg.length == 0;
  let isChange=false;
  if (IsNickName && IsSex && IsUserImg) {
    message.error("未修改信息");
    return;
  }
  if (!IsUserImg) {
    let formData = new FormData();
    formData.append("user_id", userInfo.value.id);
    formData.append("userImg", editForm.value.userImg[0].file);
    await fetch(store.state.baseURL + "api/post_user_img/", {
      method: "POST",
      body: formData,
    }).then((fetchRes) => {
      fetchRes.json().then((res) => {
        if (res?.code === 200) {
          isChange=true;
        } else {
          message.error("头像修改失败");
        }
      });
    });
  }
  if (IsNickName && IsSex) {
    await request({
      url: "/post_userInfo_change/",
      method: "POST",
      data: {
        sex: editForm.value.sex,
        nickName: editForm.value.nickName,
        user_id: userInfo.value.id,
      },
    }).then(async (res) => {
      if (res?.code == 200) {
        isChange=true;
      } else {
        message.error("更新失败");
      }
    });
  }
  if (isChange) {
    message.success("更新成功");
    showEditModal.value = false;
    await getUserInfo();
  }
};

const handleUploadChange = (options) => {
  const { file } = options;
  // 验证文件类型
  if (!["image/jpeg", "image/png", "image/gif"].includes(file.file?.type)) {
    message.error("只能上传图片文件！");
    return;
  }
  // 验证文件大小（例如限制为2MB）
  if (file.file?.size > 2 * 1024 * 1024) {
    message.error("图片大小不能超过2MB！");
    return;
  }
  // 这里可以处理图片上传逻辑
  editForm.value.userImg = file.file;
};

const handleLogout = () => {
  //退出登录
  store.commit("setUserInfo", null);
  store.commit("setLoginInfo", null);
  localStorage.clear();
  router.push("/login");
};
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.user {
  padding: 2rem $mainPadding;
  width: clamp(200px, 90%, 1000px);
  margin: 0 auto;

  .user-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    .user-header {
      display: flex;
      gap: 2rem;
      padding: 2rem;
      border-bottom: 1px solid #eee;
      position: relative;
      .logout-btn {
        position: absolute;
        right: 1rem;
        bottom: 1rem;
      }
      .user-info-change {
        position: absolute;
        right: 1rem;
        top: 1rem;
        .iconfont {
          font-weight: bold;
        }
      }

      .user-avatar {
        position: relative;

        .user_img {
          width: 120px;
          height: 120px;
          border-radius: 50%;
          border: 3px solid #fff;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          overflow: hidden;
          transition: all 0.3s ease;
          cursor: pointer;

          &:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
          }
        }

        .user-sex {
          position: absolute;
          right: 0;
          bottom: 0.5rem;
          padding: 8px;

          .iconfont {
            font-size: 16px;
          }
        }
      }

      .user-details {
        flex: 1;

        .user-name {
          display: flex;
          align-items: center;
          gap: 1rem;
          margin-bottom: 0.5rem;

          h2 {
            margin: 0;
            font-size: 1.8rem;
            color: #333;
          }
        }

        .user-id {
          color: #999;
          font-size: 0.9rem;
          margin-bottom: 1.5rem;
        }

        .user-stats {
          display: flex;
          gap: 2rem;
          flex-wrap: wrap;

          .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            transition: all 0.3s ease;

            &:hover {
              background: rgba($baseColor, 0.1);
              transform: translateY(-2px);
            }

            .number {
              font-size: 1.2rem;
              font-weight: bold;
              color: $baseColor;
            }

            .label {
              font-size: 0.9rem;
              color: #666;
              margin-top: 0.2rem;
            }
          }
        }
      }
    }

    .user-tabs {
      .tab-content {
        padding: 1rem;

        .tab-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 1rem;
          padding: 0 1rem;

          .tab-title {
            font-size: 1.1rem;
            font-weight: 500;
            color: #333;
          }
        }

        .video-list {
          padding: 1rem;
        }
      }
    }
  }
}
</style>
